package com.gitee.kamismile.stoneComEx.util;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import com.gitee.kamismile.stoneComEx.util.view.ExcelBean;
import com.gitee.kamismile.stone.commmon.util.ValueUtils;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

/**
 * Created by IntelliJ IDEA.
 * User: lidong
 * Date: 12-3-10
 * Time: 下午1:59
 * To change this template use File | Settings | File Templates.
 */
public class ExcelUtil {
    protected final Logger logger =LoggerFactory.getLogger(getClass());
    int excleNum = 60000;
    private Font headFont;
    private CellStyle headStyle;
    private CellStyle tableBodyStyle;
    private Font TableBodyFont;

    public ExcelUtil setExcleNum(int excleNum) {
        this.excleNum = excleNum;
        return this;
    }

    public void expDatas(SXSSFWorkbook workbook, List<ExcelBean> excelBeans) {
        for (ExcelBean excelBean : excelBeans) {
            writeData(workbook, excelBean);
        }
    }

    public void expData(SXSSFWorkbook workbook, ExcelBean excelBean) {
        writeData(workbook, excelBean);
    }

    private void writeData(SXSSFWorkbook workbook, ExcelBean excelBean) {

        if (headFont == null) getDefHeadFont(workbook);
        if (headStyle == null) getDefHeadStyle(workbook);
        if (tableBodyStyle == null) getBodyStyle(workbook);

        if (excelBean.getViewCtrl().equals("generalExcel")) {
            generalExcel(workbook, excelBean);
        }


    }


    private void generalExcel(SXSSFWorkbook workbook, ExcelBean excelBean) {
        Sheet sheet = null;
        List<String[][]> colmons = excelBean.getMuchColmons();
        int rowNumber = 0;
        int i = 0;
        for (int colmonNum = 0; colmonNum < colmons.size(); colmonNum++) {
            List<Map<String, Object>> maps = excelBean.getMaps().get(colmonNum);
            for (i = 0; i < ((maps.size() / excleNum) + ((maps.size() % excleNum) != 0 ? 1 : 0) + (maps.size() == 0 ? 1 : 0)); i++) {
                String sheetName = excelBean.getSheetName() + "_【" + i + "】";
                boolean hasOne = (null == workbook.getSheet(sheetName));

                sheet = (hasOne)
                        ? workbook.createSheet(sheetName)
                        : workbook.getSheet(sheetName);
                sheet.setDefaultColumnWidth(20);
                LinkedList<Map<String, Object>> tempList = new LinkedList<Map<String, Object>>();
                tempList.addAll(maps.subList(i * excleNum + 0, (i * excleNum + excleNum) > maps.size() ? maps.size() : (i * excleNum + excleNum)));
                rowNumber = createColmon(sheet, colmons, hasOne ? 0 : rowNumber, colmonNum, tempList);
            }
        }


    }

    private int createColmon(Sheet sheet, List<String[][]> colmons, int rowNumber, int colmonNum, List<Map<String, Object>> maps) {
        Row row;
        row=null;
        for(int col =0 ;col<colmons.get(colmonNum).length;col++){
            if(row==null) row=sheet.createRow(rowNumber);
            Cell cell = row.createCell(col);
            cell.setCellStyle(headStyle);
            cell.setCellValue(new XSSFRichTextString(colmons.get(colmonNum)[col][1]));
        }

        rowNumber++;

        if(maps.isEmpty()) return rowNumber;

        for(int i=0; i <maps.size() ;i++){
            row=sheet.createRow(rowNumber);
            for(int col =0 ;col<colmons.get(colmonNum).length;col++){
                //其余一般列
                Cell cell = row.createCell((col));
                cell.setCellStyle(tableBodyStyle);
                cell.setCellValue(new XSSFRichTextString
                        (ValueUtils.isStringNull(
                                maps.get(i).get(
                                        colmons.get(colmonNum)[col][0]),"")));


            }
            rowNumber++;
        }
        rowNumber++;
        return rowNumber;
    }



    private void getBodyStyle(SXSSFWorkbook workbook) {
        tableBodyStyle = workbook.createCellStyle();
        tableBodyStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
        tableBodyStyle.setBorderTop(BorderStyle.THIN);
        tableBodyStyle.setBorderBottom(BorderStyle.THIN);
        tableBodyStyle.setBorderLeft(BorderStyle.THIN);
        tableBodyStyle.setBorderRight(BorderStyle.THIN);
        tableBodyStyle.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        tableBodyStyle.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        tableBodyStyle.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        tableBodyStyle.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//        tableBodyStyle.setWrapText(true);
    }

    private void getDefHeadStyle(SXSSFWorkbook workbook) {
        XSSFCellStyle xheadStyle = (XSSFCellStyle) workbook.createCellStyle();
        xheadStyle.setFont(headFont);
        xheadStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        xheadStyle.setAlignment(HorizontalAlignment.CENTER);
//        headStyle.setWrapText(true);
        xheadStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        xheadStyle.setFillForegroundColor( new XSSFColor(new byte[]{(byte)102,(byte)102,(byte)153}));
        this.headStyle = xheadStyle;
    }

    private void getDefHeadFont(SXSSFWorkbook workbook) {
        headFont = workbook.createFont();
        headFont.setBold(true);
        headFont.setColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
    }


    public Font getHeadFont() {
        return headFont;
    }

    public void setHeadFont(XSSFFont headFont) {
        this.headFont = headFont;
    }

    public CellStyle getHeadStyle() {
        return headStyle;
    }

    public void setHeadStyle(XSSFCellStyle headStyle) {
        this.headStyle = headStyle;
    }

    public CellStyle getTableBodyStyle() {
        return tableBodyStyle;
    }

    public void setTableBodyStyle(XSSFCellStyle tableBodyStyle) {
        this.tableBodyStyle = tableBodyStyle;
    }

    public Font getTableBodyFont() {
        return TableBodyFont;
    }

    public void setTableBodyFont(XSSFFont tableBodyFont) {
        TableBodyFont = tableBodyFont;
    }


    public void addBackgroundImgToExcel(Workbook workbook, ExcelBean excelBean) {
        if (excelBean.isWaterMark()) {
            try {
                File waterMarkImg = createWaterMark(excelBean.getWaterMarkMsg());
                byte[] imageData = new byte[(int) waterMarkImg.length()];
                FileInputStream fis = new FileInputStream(waterMarkImg);
                fis.read(imageData);
                fis.close();
                int id = workbook.addPicture(imageData, Workbook.PICTURE_TYPE_PNG);
                excelBean.setWaterMarkMsgURI(((XSSFPictureData) workbook.getAllPictures().get(id)).getPackagePart().getPartName().getURI());
            } catch (Exception e) {
                logger.error("生成背景图片报错" + e.getMessage());
            }
        }
    }


    public static File createWaterMark(String watermark) throws IOException {
        File outputFile = File.createTempFile("warterMark", "png");
        int width = 600; // 水印图片的宽度
        int height = 200; // 水印图片的高度 因为设置其他的高度会有黑线，所以拉高高度

        // 获取bufferedImage对象
        BufferedImage bi = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 处理背景色，设置为 白色
        int minx = bi.getMinX();
        int miny = bi.getMinY();
        for (int i = minx; i < width; i++) {
            for (int j = miny; j < height; j++) {
                bi.setRGB(i, j, 0xffffff);
            }
        }

        // 获取Graphics2d对象
        Graphics2D g2d = bi.createGraphics();
        // 设置字体颜色为灰色
        g2d.setColor(new Color(240, 240, 240));
        // 设置图片的属性
        g2d.setStroke(new BasicStroke(1));
        // 设置字体
        g2d.setFont(new java.awt.Font("华文细黑", java.awt.Font.ITALIC, 50));
        // 设置字体倾斜度
        g2d.rotate(Math.toRadians(-10));

        // 写入水印文字 原定高度过小，所以累计写水印，增加高度
        for (int i = 1; i < 26; i++) {
            g2d.drawString(watermark, 0, 40 * i);
        }
        // 设置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 释放对象
        g2d.dispose();
        ImageIO.write(bi, "png", outputFile);

        return outputFile;
    }


}
